from flask_login import login_required

from ..base import base
from flask import request
from ..service.NewsService import *
from exts import success, page_success


@base.route('/api/news/add', methods=['POST'])
@login_required
def news_add_api():
    '''
    新闻接口
    :return:
    '''
    news = request.get_json()
    news_add(news)
    return success(news)


@base.route('/api/news/update', methods=['POST'])
def news_update_api():
    '''
    更新新闻
    :return:
    '''
    news = request.get_json()
    news_update(news)
    return success(news)


@base.route('/api/news/detail', methods=['POST'])
def news_detail_api():
    '''
    新闻详情
    :return:
    '''
    news = request.get_json()
    return success(news_detail(news['id']).to_json())


@base.route('/api/news/delete', methods=['POST'])
def news_delete_api():
    '''
    删除新闻
    :param id:
    :return:
    '''
    news = request.get_json()
    news_delete(news['id'])
    return success(news['id'])


@base.route('/api/news/page', methods=['GET'])
def news_page_api():
    '''
    分页新闻
    :return:
    '''
    pageNum = request.args.get('pageNum', 1, type=int)
    pageSize = request.args.get('pageSize', 1, type=int)
    page = news_page(pageNum, pageSize)
    news = [new.to_json() for new in page.items]
    return page_success(page.total, news)


# ===================================pc web端api接口====================================================
@base.route('/api/news/list', methods=['GET'])
def news_list_api():
    '''
    新闻列表
    :return:
    '''
    news = News.query.all()
    return success([o.to_json() for o in news])
